package com.ntd.study.lazy;

import java.util.function.Supplier;

/**
* 为了方便与标准的 Java 函数式接口交互，NtdLazy 也实现了 Supplier
*/
public class NtdLazy<T> implements Supplier<T> {

    private final Supplier<? extends T> supplier;
    
    // 利用 value 属性缓存 supplier 计算后的值
    private T value;

    private NtdLazy(Supplier<? extends T> supplier) {
        this.supplier = supplier;
    }

    public static <T> NtdLazy<T> of(Supplier<? extends T> supplier) {
        return new NtdLazy<>(supplier);
    }

    public T get() {
        if (value == null) {
            return this.initVal();
        }
        return value;
    }

    public T initVal() {
        T newValue = supplier.get();

        if (newValue == null) {
            throw new IllegalStateException("NtdLazy value can not be null!");
        }

        value = newValue;

        return value;
    }
}